package jdbc;

import com.sun.xml.internal.bind.v2.model.core.ID;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/*
* 执行INSERT语句
* */
public class JDBCDemo2 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                "root",
                "root"
        );
        System.out.println("成功连接数据库!");
        Statement statement = connection.createStatement();

        /*
           INSERT INTO userinfo(username,password,nickname,age)
           VALUES('张三','123456','阿三',22)
         */

        String sql="INSERT INTO userinfo(username,password,nickname,age) " +
                   "VALUES('张三','123456','阿三',22)";

        //执行sql语句(之所以是int 是因为执行INSERT语句插入一条数据，返回值是1)
        /*
         * Statement 提供了用于执行dml语句的方法：
         * int executeUpdate(String sql)
         * 该方法执行后会返回一个int 值，表示执行dml草祖宗后影响了表中多条记录
         * */
        int num = statement.executeUpdate(sql);
        if (num>0){//判断是否插入成功
            System.out.println("插入成功!");
        }
        connection.close();//关闭连接
    }
}
